<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn({})"></jk-add-button>
					<!--<jk-report-button :permission-prefix="prefix" class="margin-5-0" :loading="exportLoading" @click="onReportBtn"></jk-report-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.auditState" :option-list="auditStateList" placeholder="状态" clearable size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-search-input v-model="searchParams.nameOrCode" placeholder="编码或名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>
		<jk-card v-loading="tableLoading" :style="{ height: `${tableHeight + 60}px`, overflow: 'auto' }">
			<el-tree
				:data="treeData"
				highlight-current
				:props="{
					children: 'children',
					value: 'id',
					label: 'nameAndCode'
				}"
				:load="loadNode"
				lazy
			>
				<div slot-scope="{ node, data }" class="custom-tree-node">
					<div>{{ node.label }}</div>
					<div class="flex-start-center" style="font-size: 12px;border-left: solid 1px #eee;padding-left: 30px;">
						<div style="width: 100px;">损耗: {{ data.loss || '0' }}</div>
						<div style="width: 140px;">存货类型: {{ data.typeName }} {{ data.creatorName }}</div>
						<!--<div style="width: 250px;">创建 {{ data.createTime }} {{ data.creatorName }}</div>-->
						<!--<div style="width: 250px;">修改 {{ data.updateTime }} {{ data.updaterName }}</div>-->
						<div class="margin-right-10"><jk-common-status :status="data.auditState"></jk-common-status></div>
						<div><el-button type="text" size="mini" :icon="data.auditState ? 'el-icon-video-pause' : 'el-icon-video-play'" @click="onStateChangeBtn(data)">{{ data.auditState ? '撤销' : '审核' }}</el-button></div>
						<div><el-button type="text" size="mini" icon="el-icon-plus" @click="onAddBtn(data)">新增</el-button></div>
						<div><el-button :disabled="!!data.auditState" type="text" size="mini" icon="el-icon-edit" @click="onEditBtn(data)">编辑</el-button></div>
						<el-button :disabled="!!data.auditState" type="text" size="mini" icon="el-icon-delete-solid" @click="onDeleteBtn(data)">删除</el-button>
					</div>
				</div>
			</el-tree>
		</jk-card>
		<detail-dialog
			:data-id="dataId"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChangeOfDetailDialog"
		></detail-dialog>
		<save-dialog
			:permission-prefix="prefix"
			:data-id="dataId"
			:select-tree-id="selectTreeId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import detailDialog from './detail-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { createTree, pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import {
        spinProductCategoryDelete,
        spinProductCategoryPage,
        spinProductCategoryExportExcel,
        spinProductCategoryList, spinProductCategoryUpdateAuditState
    } from '/src/api/material/category';
    import { auditStateList } from '../../../utils/jk/status-option-list';

    export default {
        name: 'MaterialCategory',
        components: {
            saveDialog,
            detailDialog
        },
        mixins: [calHeight],
        data() {
            return {
                apiItem: {
                    'page': spinProductCategoryPage,
                    'list': spinProductCategoryList,
                    'exportExcel': spinProductCategoryExportExcel,
                    'delete': spinProductCategoryDelete
                },
                selectTreeId: null,
                treeData: [],
                detailDialogState: false,
                prefix: 'spin:productCategory',
                auditStateList: auditStateList,
                dataId: null,
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    // pageSize: pageConfig.pageSize,
                    pageSize: 1000,
                    nameOrCode: '',
                    auditState: null,
                    parentId: 0
                }
            };
        },
        mounted() {
            this.getDependentData();
        },
        methods: {
            loadNode(node, resolve) {
                if (node.level === 0) {
                    return resolve([{ name: 'region' }]);
                }
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.parentId = node.data.id;
                return this.apiItem['list'](params).then(res => {
                    if (res.data.status === 200) {
                        const list = res.data.res ? res.data.res.map(x => {
                            x.nameAndCode = `${x.code} ${x.name}`;
                            x.leaf = false;
                            return x;
                        }) : [];
                        resolve(list);
                    }
                });
            },
            getListRequest() {
                this.tableLoading = true;
                return this.apiItem['list'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        const list = res.data.res ? res.data.res.map(x => {
                            x.nameAndCode = `${x.code} ${x.name}`;
                            return x;
                        }) : [];
                        let arr = [];
                        arr = createTree(list, {});
                        this.treeData = arr;
                    }
                });
            },
            onStateChangeBtn(data) {
                this.$confirm(`确认 "${data.auditState ? '停用' : '启用'}" ？`, {
                    title: '提示',
                    iconClass: 'el-icon-question'
                }).then(res => {
                    if (res === 'confirm') {
                        spinProductCategoryUpdateAuditState({ id: data.id }).then(res => {
                            if (res.data.status === 200) {
                                this.$emit('on-refresh');
                                this.getListRequest();
                                tipsBar(this, 'operation');
                            }
                        });
                    }
                });
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            handleNodeClick(e) {
                this.deptId = e.id;
                if (e.children && e.children.length !== 0) {
                    this.selectTreeId = e.id;
                    // this.selectTreeId = null;
                } else {
                    this.selectTreeId = e.id;
                }
                // this.$set(this.searchParams, 'parentId', this.selectTreeId);
                this.searchParams.categoryId = e.id;
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(e) {
                this.dataId = e.id;
                this.detailDialogState = true;
            },
            onVisibleChangeOfDetailDialog(e) {
                this.detailDialogState = e;
                if (!e) {
                    this.dataId = null;
                }
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.saveDialogState = e;
                if (!e) {
                    this.dataId = null;
                }
            },
            /** 新增按钮操作 */
            onAddBtn(data) {
                this.selectTreeId = data.id;
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.saveDialogState = true;
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.$confirm('确定删除吗?', { type: 'warning' }).then(() => {
                    this.apiItem['delete']({ id: row.id }).then((res) => {
                        if (res.data.status === 200) {
                            this.getListRequest();
                            this.$tipsBar(this, 'delete');
                        }
                    });
                });
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = { ...this.searchParams };
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有班组数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem['exportExcel'](params);
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$download.excel(res, `${this.$route.meta.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            }
        }
    };
</script>
<style scoped lang="scss">
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>
